package com.hoas.api.encrypt;


import com.hoas.api.encrypt.type.Base64;
import com.hoas.api.encrypt.type.rsa.RSAEncrypt;

import java.security.PrivateKey;
import java.security.PublicKey;

public class EncryptUtil {

	private String encryptType;

	private PrivateKey privateKey;

	private PublicKey publicKey;

	public EncryptUtil(String encryptType, String publicKey, String privateKey) throws Exception {

		this.encryptType = encryptType;
		this.privateKey = RSAEncrypt.string2PrivateKey( privateKey );
		this.publicKey = RSAEncrypt.string2PublicKey( publicKey );
	}

	/**
	 * 私钥解密
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public String decrypt( String content) throws Exception{
		
	    try
        {
            if ( EncryptType.RSA.toString().equals( this.encryptType ) )
            {
                content = Base64.encode(RSAEncrypt.decrypt(this.privateKey, content.getBytes()));
            }
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return content;
		
	}
	
	/**
	 * 公钥加密
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public String encrypt( String content) throws Exception{
		
        if ( EncryptType.RSA.toString().equals( this.encryptType ) )
        {
            return new String(RSAEncrypt.encrypt(this.publicKey, Base64.decode(content)));
        }

        return content;
		
	}

}
